/*
  Copyright 2011 Jonathan Albarrán León

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.jaal.movilconsultanet.asynctasks;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.jaal.movilconsultanet.Progreso;
import com.jaal.movilconsultanet.R;
import com.jaal.movilconsultanet.SessionCookie;
import com.jaal.movilconsultanet.activities.MovilConsultaNet;

public class CaptchaRequester extends AsyncTask<String, Progreso, Drawable> {

	MovilConsultaNet mainActivity;
	ProgressDialog progreso;
	Progreso progresoInfo = new Progreso();

	public CaptchaRequester(MovilConsultaNet mainActivity) {
		this.mainActivity = mainActivity;
	}

	protected void onPreExecute() {
		progreso = new ProgressDialog(mainActivity);
		progreso.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progreso.setProgress(0);
		progreso.setMessage(mainActivity.getResources().getText(R.string.connection_connecting_server));
		progreso.setCancelable(false);
		progreso.show();
		}

	protected Drawable doInBackground(String... urls) {

		String targetURL = urls[0];
		SessionCookie sessionCookie = mainActivity.getSessionCookie();
		HttpURLConnection connection = null;

		Log.d("MCN", "CaptchaRequester - inicio");

		URL url;
		try {
			// Create connection
			url = new URL(targetURL);

			progresoInfo.setProgreso(20);
			progresoInfo.setMensaje(mainActivity,R.string.connection_connecting);
			publishProgress(progresoInfo);
			
			Log.d("MCN", "CaptchaRequester - conectando..." + targetURL);
			connection = (HttpURLConnection) url.openConnection();
			
			connection.setConnectTimeout(3000);
			
			connection.connect();
			
			progresoInfo.setProgreso(40);
			progresoInfo.setMensaje(mainActivity,R.string.connection_accessing);
			publishProgress(progresoInfo);
			String JSessionId = connection.getHeaderField(3);
			Log.d("MCN", "CaptchaRequester - getJSessionCookie... "+JSessionId);
			
			sessionCookie.setSessionCookie(JSessionId);
			Log.d("MCN","CaptchaRequester - setSessionCookie: "+ sessionCookie.getSessionCookie());

			progresoInfo.setProgreso(75);
			progresoInfo.setMensaje(mainActivity,R.string.connection_get_captcha);
			publishProgress(progresoInfo);

			Log.d("MCN","CaptchaRequester - getContent");
			InputStream is = (InputStream) connection.getContent();
			
			Log.d("MCN","CaptchaRequester - createFromStream");
			
			progresoInfo.setProgreso(90);
			progresoInfo.setMensaje(mainActivity,R.string.connection_create_captcha);
			publishProgress(progresoInfo);

			Drawable image = Drawable.createFromStream(is, "src name");

			progresoInfo.setProgreso(100);
			progresoInfo.setFinished(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_final);
			publishProgress(progresoInfo);
			
			is.close();
			
			return image;
		} catch (ConnectException e) {
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error);
			publishProgress(progresoInfo);
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error_server);
			publishProgress(progresoInfo);
		} catch (IOException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error_io);
			publishProgress(progresoInfo);
		} finally {
			if (connection != null) {
				Log.d("MCN", "CaptchaRequester - desconectando...");
				connection.disconnect();
			}
		}
		Log.d("MCN", "CaptchaRequester - fin NO SE PUDO DESCARGAR IMAGEN");
		return null;
	}

	@Override
	protected void onProgressUpdate(Progreso... values) {
		
		Progreso mProgresoInfo = values[0];
		
		if (!mProgresoInfo.isError()) {
			progreso.setProgress(mProgresoInfo.getProgreso());
			progreso.setMessage(mProgresoInfo.getMensaje());
			
			if (mProgresoInfo.isFinished()) {
				progreso.dismiss();
			}
			
		} else {
			progreso.dismiss();
			Toast.makeText(mainActivity, mProgresoInfo.getMensaje(), Toast.LENGTH_SHORT).show();
		}
		
	}

	protected void onPostExecute(Drawable result) {

		if (progresoInfo.isError()) {
			return;
		}
		
		
		AlertDialog.Builder builder;
		AlertDialog alertDialog;

		Context mContext = mainActivity;
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		final View layout = inflater
				.inflate(R.layout.captcha_dialog, (ViewGroup) mainActivity
						.findViewById(R.id.captcha_layout_root));

		ImageView image = (ImageView) layout.findViewById(R.id.captchaImage);
		image.setImageDrawable(result);

		builder = new AlertDialog.Builder(mContext);
		builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
//				Intent i = new Intent(mainActivity, ConsultaSaldo.class);
//				i.putExtra("session", mainActivity.getSessionCookie().getSessionCookie());
//				mainActivity.startActivity(i);
		
				EditText textoCaptcha = (EditText) layout.findViewById(R.id.editTextCaptcha);
				
				String mCaptcha = textoCaptcha.getText().toString().trim();
				
				new GSMSessionStarter(mainActivity).execute(mCaptcha);
				
			}
		}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		})
		.setIcon(R.drawable.ic_dialog_dialer);

		builder.setView(layout);
		alertDialog = builder.create();

		alertDialog.setTitle(R.string.hint_captcha);

		alertDialog.show();

		// showDialog("Downloaded " + result + " bytes");
	}
}